package com.cn.transfer.aop;

import com.cn.transfer.myanno.MyAutowired;
import com.cn.transfer.utils.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class MyTransactionalAop {

    @MyAutowired("transactionManager")
    private TransactionManager transactionManager;

    // 定义切点
    @Pointcut("@annotation(com.cn.transfer.myanno.MyTransactional)")
    public void transactionAop() {

    }

    @Around(value = "transactionAop()")
    public Object around(ProceedingJoinPoint joinPoint) throws Exception {
        Object proceed = null;

        System.out.println("进入环绕增强方式");
        transactionManager.beginTransaction();
        try {
            proceed = joinPoint.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            transactionManager.rollback();
            throw new Exception(throwable);
        } finally {
            System.out.println("执行 finally 程序");
        }
        transactionManager.commit();

        return proceed;
    }

}
